<?php

class SearchController extends Controller
{
    public $searchSelectCategories = array();
    public $searchedCategories = array();
    public $aCategoriesCounts = array();
    public $q = '';

	public function actionSearch($q = null)
	{
        $this->q = String::stripTagsAttributes($q);

		$oSphinx = new SphinxClient();

		$oSphinx->SetMatchMode(SPH_MATCH_EXTENDED);
		$oSphinx->SetFilterRange('status', 1, 2);

        if($this->_getParam('c'))
        {
            $oCategories = new Categories();
            $oCategory = $oCategories->findByAttributes(array(
                'alias' => $this->_getParam('c')
            ));

            if(!empty($oCategory))
            {
                $this->searchSelectCategories[$oCategory['id']] = $oCategory['id'];
                $oSphinx->SetFilter('category_id', array($oCategory['id']));
            }
        }

		$oSphinx->SetWeights(array(
//		                          'code' => 100,
		                          'title' => 90,
		                          //'property_title' => 90,
		                          'description' => 80,
		                          'short_description' => 80,
		                          'price' => 75,
		                     ));

		$query = $this->q;
		$query = mb_strtolower($query, 'UTF-8');
		$query = $query .' | '.String::correctString($this->q);
		$oSphinx->AddQuery($query, 'goods_text');

		$oSphinx->ResetFilters();
		$oSphinx->ResetGroupBy();
		$oSphinx->SetFilterRange('status', 1, 2);
		$oSphinx->SetGroupBy('category_id', SPH_GROUPBY_ATTR);
		$oSphinx->AddQuery($query, 'goods_text');

		$aResult = $oSphinx->RunQueries();

		$ids = array();
		$categoryIds = array();
		$categoriesCounts = array();

//		print_r($aResult); exit;

		if(!empty($aResult))
		{
			foreach($aResult as $i => $aRow)
			{
				if(!empty($aRow['matches']))
				{
					foreach($aRow['matches'] as $id => $attr)
					{
                        if($i == 0)
						    $ids[$id] = $id;
						elseif($i == 1)
							$this->aCategoriesCounts[$attr['attrs']['category_id']] = $attr['attrs']['@count'];

						$categoryIds[$attr['attrs']['category_id']] = $attr['attrs']['category_id'];
					}
				}
			}
		}

		$this->searchedCategories = $categoryIds;
//		$this->searchSelectCategories = $categoryIds;
//print_r($categoryIds);
//		print_r($aResult); exit;

//        echo $q;
        $oGoods = new Goods();
        $oPhotos = new Photos();
        $oCategories = new Categories();

        if(!isset($aResult[0]) || !isset($aResult[0]['total_found']))
        {
			$this->oPager->setItemCount(0);
        }
		else
			$this->oPager->setItemCount($aResult[0]['total_found']);


		if($this->_isXmlHttpRequest())
		{
			$this->oPager->setPageSize(10);
			$oRowset = $oGoods->group('title')->getListByParentId($ids, $this->oPager, false);

            $this->layout='//layouts/ajax';
			return $this->render('search-ajax', array(
			                                    'oRowset' => $oRowset,
			                               ));
		}

		$this->oPager->setPageSize(50);
		$oRowset = $oGoods->getListByParentId($ids, $this->oPager, false);

		$oPhotos->selectMainByRowset($oRowset);
        $oCategories = $oCategories->id($categoryIds)->onlyPublic()->findAll();

		// Breadcrumbs
		$this->breadcrumbs[_('Поиск').' "'. $this->q .'"'] = Yii::app()->createUrl('/cart', array());

        $this->layout='//layouts/main-left';
		$this->render('search', array(
		                             'oRowset' => $oRowset,
                                     'oCategories' => $oCategories
		                        ));
	}




}